package com.cms.ctrl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.cms.service.CommandService;

@Controller
@RequestMapping("/comm")
public class CommCtrl {
	
	private String convert(Object obj){
		if(obj instanceof List){
			return JSONArray.fromObject(obj).toString();
		}else{
			return JSONObject.fromObject(obj).toString();
		}
	}
	
	@RequestMapping(value = "/{cmd}")
	public @ResponseBody String exec(HttpServletRequest request, HttpServletResponse response, @PathVariable String cmd){
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		CommandService service=(CommandService)webApplicationContext.getBean(cmd);
		return convert(service.exec(request, response));
	};
}
